const addButtonListen = (node, call, func) =>{
	let button = node.getComponent(cc.Button)
	if(!button){
		return
	}
	node.on('click', func, call)
}

const loadPrefab = (parent, prefabName) => {
	cc.resources.load('prefabs/' + prefabName, (err, prefab)=>{
		let item = cc.instantiate(prefab)
		parent.addChild(item)
		item.addComponent(prefabName)
	})
}

const array2Tree = (arr, fid = 'fid') => {
	arr.forEach(v => {
		let fv = v[fid]
		if (fv > 0) {
			arr.forEach(vv => {
				if (vv.id == fv) {
					if (!vv.children) {
						vv.children = []
					}
					vv.children.push(v)
				}
			})
		}
	})
	return arr.filter(vv => !vv[fid] || vv[fid] == 0)
}

const cache = (name, value = '', time = 3600) => {
	let sign = md5Libs.md5(name)
	if (value) {
		let cachetime = Date.parse(new Date()) / 1000 + time
		let cache = {
			data: value,
			time: cachetime
		}
		uni.setStorageSync(sign, JSON.stringify(cache))
		return true
	} else if (value === null) {
		uni.removeStorageSync(sign)
		return true
	} else {
		let time = Date.parse(new Date()) / 1000
		let json = uni.getStorageSync(sign)
		if (json) {
			let cache = JSON.parse(json || '{}')
			if (cache.time > 0 && cache.time > time) {
				return cache.data
			} else {
				uni.removeStorageSync(sign)
			}
		}
	}
	return false
}

module.exports = {
    array2Tree,
    cache,
	addButtonListen,
	loadPrefab
}